#include "Structs.hpp"
using namespace std;

// 初始化未合成树链表
NoMergeTreeList *initNoMergeTreeList()
{
  NoMergeTreeList *noMergeTreeList = new NoMergeTreeList;
  noMergeTreeList->next = nullptr;
  noMergeTreeList->length = 0;
  return noMergeTreeList;
}

// 插入未合成树
void insertNoMergeTree(NoMergeTreeList *list, Node *noMergeTree)
{
  auto *newNode = new NoMergeTreeNode;
  newNode->noMergeTree = noMergeTree;
  newNode->next = nullptr;
  if (list->next == nullptr)
  {
    list->next = newNode;
    list->length++;
    return;
  }
  NoMergeTreeNode *node = list->next;
  while (node->next != nullptr)
  {
    node = node->next;
  }
  node->next = newNode;
  list->length++;
}

// 删除未合成树节点
void delNoMergeTree(NoMergeTreeList *list, int data)
{
  NoMergeTreeNode *noMergeTreeNode = list->next;
  if (noMergeTreeNode->noMergeTree->data == data)
  {
    list->next = noMergeTreeNode->next;
    list->length--;
    delete noMergeTreeNode;
    return;
  }
  // 找到一个点：它的下一个节点的树为要删除的树
  while (noMergeTreeNode->next->noMergeTree->data != data)
  {
    noMergeTreeNode = noMergeTreeNode->next;
  }
  NoMergeTreeNode *deleteNode = noMergeTreeNode->next;
  noMergeTreeNode->next = deleteNode->next;
  list->length--;
  delete deleteNode;
}

// 匹配
Result *match(NoMergeTreeList *list, int minFirst, int minSecond)
{
  // 权值：  first匹配 1   second匹配 2
  int count = 0;
  bool isFirstMatched = false;
  bool isSecondMatched = false;
  NoMergeTreeNode *node = list->next;
  Result *result = new Result;
  while (node != nullptr && list->length > 0)
  {
    if (node->noMergeTree->data == minFirst && !isFirstMatched)
    {
      result->firstTree = node->noMergeTree;
      count += 1;
      // 删除节点
      delNoMergeTree(list, minFirst);
      isFirstMatched = true;
      node = list->next;
      continue;
    }
    if (node->noMergeTree->data == minSecond && !isSecondMatched)
    {
      result->secondTree = node->noMergeTree;
      count += 2;
      // 删除节点
      delNoMergeTree(list, minSecond);
      isSecondMatched = true;
      node = list->next;
      continue;
    }
    node = node->next;
  }
  result->count = count;
  return result;
}